/**
 * Copyright (C) <2023> <Boundivore> <boundivore@foxmail.com>
 * <p>
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the Apache License, Version 2.0
 * as published by the Apache Software Foundation.
 * <p>
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * Apache License, Version 2.0 for more details.
 * <p>
 * You should have received a copy of the Apache License, Version 2.0
 * along with this program; if not, you can obtain a copy at
 * http://www.apache.org/licenses/LICENSE-2.0.
 */
import { useSearchParams } from 'react-router-dom';
import _ from 'lodash';
import { Modal, Flex, Card, Col, Row, Tabs, Typography, Popover, Button, App } from 'antd';
import type { TabsProps } from 'antd';
import { ExclamationCircleFilled } from '@ant-design/icons';
import RequestHttp from '@/api';
import APIConfig from '@/api/config';
import { t } from 'i18next';
import { useEffect, useState } from 'react';
import Base64 from 'crypto-js/enc-base64';
import Utf8 from 'crypto-js/enc-utf8';
import FullscreenDiffViewer from './fullscreenDiffViewer';
import { useConfigState } from '../hooks/useConfigState';
import { ConfigHistoryVersionSummaryVo } from '@/api/interface';
import { findNodeInArray } from '@/utils/helper';
import { useFileContent } from '../hooks/useFileContent';
import { MessageInstance } from 'antd/es/message/interface';
const { Paragraph } = Typography;
interface RollbackModalProps {
	isModalOpen: boolean;
	handleCancel: () => void;
	fileName: string;
	messageApi: MessageInstance;
	callback: () => void;
}

type TabItem = NonNullable<TabsProps['items']>[number] & ConfigHistoryVersionSummaryVo;

const RollbackModal: React.FC<RollbackModalProps> = ({ isModalOpen, handleCancel, fileName, messageApi, callback }) => {
	const [searchParams] = useSearchParams();
	const id = searchParams.get('id');
	const serviceName = searchParams.get('name') || '';
	const { configPath, currentNodeId, configGroupInfo, setConfigGroupInfo } = useConfigState();
	const [configData, setConfigData] = useState<ConfigHistoryVersionSummaryVo[]>([]);
	const [tabsData, setTabsData] = useState<TabItem[]>([]);
	const [activeTab, setActiveTab] = useState<string>('');
	const [codeEdit, setCodeEdit] = useState<string>('');
	const [targetConfigData, setTargetConfigData] = useState<string>('');
	const [targetSha256, setTargetSha256] = useState<string>('');
	const [oldTime, setOldTime] = useState<string>('');
	const [newTime, setNewTime] = useState<string>('');
	const [oldVersion, setOldVersion] = useState<string>('');
	const [newVersion, setNewVersion] = useState<string>('');
	const [isSave, setIsSave] = useState<boolean>(false);
	const { saveChange } = useFileContent(messageApi, callback);
	const { modal } = App.useApp();
	const { item } = findNodeInArray(configGroupInfo, currentNodeId);
	const oldCode = Utf8.stringify(Base64.parse(item.ConfigData));

	// 获取初始数据
	const getConfigFile = async () => {
		const api = APIConfig.getConfigVersionInfo;
		const params = {
			ClusterId: id,
			NodeId: currentNodeId,
			Filename: fileName,
			ConfigPath: configPath,
			ServiceName: serviceName
		};
		const {
			Data: { ConfigHistoryVersionSummaryList }
		} = await RequestHttp.get(api, { params });

		setConfigData([...ConfigHistoryVersionSummaryList]); // 保存原始数据
	};
	const getFileContent = async () => {
		// setLoading(true);
		const api = APIConfig.getConfigVersionDetail;
		const params = {
			ClusterId: id,
			NodeId: currentNodeId,
			ServiceName: serviceName,
			Filename: fileName,
			ConfigPath: configPath,
			HistoryConfigVersion: activeTab
		};
		const data = await RequestHttp.get(api, { params });
		const {
			Data: { ConfigData, Sha256, CurrentConfigVersion, HistoryConfigVersion }
		} = data;
		const codeData = Utf8.stringify(Base64.parse(ConfigData));

		setCodeEdit(codeData);
		setTargetConfigData(ConfigData);
		setTargetSha256(Sha256);
		const preTime = tabsData.find(item => item.HistoryConfigVersion === CurrentConfigVersion)?.ConfigVersionDateTimeFormat || '';
		const curTime = tabsData.find(item => item.HistoryConfigVersion === HistoryConfigVersion)?.ConfigVersionDateTimeFormat || '';
		setNewTime(curTime);
		setOldTime(preTime);
		setOldVersion(CurrentConfigVersion);
		setNewVersion(HistoryConfigVersion);
	};
	const mergeData = () => {
		// Copy the original data

		let colneConfigGroupList = _.cloneDeep(configGroupInfo);
		const { item, node: newDataArr } = findNodeInArray(colneConfigGroupList, currentNodeId);

		const updatedConfigGroupList = [
			{
				...item,
				...{ Sha256: targetSha256, ConfigData: targetConfigData },
				...{ ConfigNodeList: [{ ...newDataArr, ConfigVersion: newVersion }] }
			}
		];

		return updatedConfigGroupList;
	};
	useEffect(() => {
		getConfigFile();
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, []);
	useEffect(() => {
		activeTab && getFileContent();
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [activeTab]);
	useEffect(() => {
		if (!configData.length) return;

		const tabs = configData.map(item => {
			return {
				...item,
				key: item.HistoryConfigVersion,
				label: (
					<Popover
						// placement="left"
						content={
							<Paragraph className="mb-0" copyable>
								{item.ConfigVersionFileName}
							</Paragraph>
						}
					>
						<span className="inline-block w-[180px] truncate text-left">{item.ConfigVersionFileName}</span>
					</Popover>
				)
			};
		});

		setTabsData(tabs);
		setActiveTab(tabs[0].key); // 默认选中第一项
	}, [configData]);
	useEffect(() => {
		isSave && saveChange(true);
		isSave && handleCancel();
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [isSave]);
	return configData.length ? (
		<Modal
			title={'回滚配置'}
			width="90%"
			className="min-w-[1000px]"
			open={isModalOpen}
			onCancel={handleCancel}
			footer={[
				<Button
					key="ok"
					type="primary"
					onClick={() => {
						modal.confirm({
							content: `您确认回滚到版本${newVersion}吗？`,
							onOk: () => {
								const data = mergeData();
								setConfigGroupInfo(data);
								setIsSave(true);
							}
						});
					}}
				>
					确认回滚
				</Button>,
				<Button key="cancel" onClick={handleCancel}>
					{t('close')}
				</Button>
			]}
		>
			<Flex gap="middle" className="w-[100%] overflow-hidden">
				<Row className="w-[100%] h-[100%] min-w-[1px]">
					<Col className="min-h-[500px]" span={4}>
						<Card title={<div className="flex items-center">配置文件名称</div>} className="w-[100%] no-padding-left">
							<Tabs
								className="h-[550px]"
								tabBarStyle={{ width: '100%' }}
								tabPosition="left"
								items={tabsData}
								onChange={activeKey => {
									setActiveTab(activeKey);
								}}
							/>
						</Card>
					</Col>

					<Col className="min-h-[500px]" span={20}>
						<Card
							title={
								<>
									<h3>{fileName}</h3>
									<Paragraph className="mb-2 text-[16px]" copyable>
										{configPath}
									</Paragraph>
								</>
							}
						>
							<FullscreenDiffViewer
								oldCode={codeEdit}
								newCode={oldCode}
								newVersion={newVersion}
								newTime={newTime}
								oldVersion={oldVersion}
								oldTime={oldTime}
							/>
						</Card>
					</Col>
				</Row>
			</Flex>
		</Modal>
	) : (
		<Modal
			open={isModalOpen}
			onCancel={handleCancel}
			footer={[
				<Button key="cancel" onClick={handleCancel}>
					{t('close')}
				</Button>
			]}
		>
			<ExclamationCircleFilled className="text-[#faad14] text-xl mr-2" />
			<span className="text-[18px] font-bold">当前配置文件在此前节点没有历史版本</span>
		</Modal>
	);
};
export default RollbackModal;
